package org.beholder;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.util.Enumeration;

/**
 * Designed to process image data sent as a body of simple Http POST request 
 * and store image in DB.
 */
public class UploadServlet extends AbstractServlet {

    private static final long serialVersionUID = 1L;
//    private ByteArrayInputStream bais = new ByteArrayInputStream();

    private Logger logger = Logger.getLogger(UploadServlet.class);

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(">>>");
        System.out.println("req.getPathInfo()="+req.getPathInfo());
        System.out.println("req.getPathTranslated()="+req.getPathTranslated());
        System.out.println("req.getRemoteAddr()=" + req.getRemoteAddr());
        System.out.println("req.getRemoteUser()=" + req.getRemoteUser());
        Enumeration e = req.getHeaderNames();
        while(e.hasMoreElements()) {
            String headerName = (String)e.nextElement();
            String headerValue = req.getHeader(headerName);
            System.out.println("Header name=" + headerName + ", value=" + headerValue);
        }
        System.out.println("<<<");
        String sessionId = req.getSession().getId();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        IOUtils.copy(req.getInputStream(), os);
        IOUtils.closeQuietly(req.getInputStream());
        System.out.println("Body:"+new String(os.toByteArray()));
        ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
        storeShot(is, sessionId);
        resp.setStatus(HttpServletResponse.SC_OK);
//        resp.setHeader("Transfer-Encoding", "chunked");
        resp.flushBuffer();
//        req.getRequestDispatcher("/list.jsp").forward(req,resp);
//        resp.sendRedirect("/post");
    }

//    @Override
////    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
//    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        InputStream is = req.getInputStream();
//        IOUtils.copy(is, System.out);
//        IOUtils.closeQuietly(is);
//        resp.getWriter().write("HTTP/1.1 200 OK\n");
//        resp.flushBuffer();
//    }

    private void storeShot(InputStream is, String sessionId) throws IOException {
        logger.info(is.available()+"bytes to upload for servlet " + this);
        logger.debug("Upload bytes available:"+is.available());
        try {
            PreparedStatement ps = conn.prepareStatement("INSERT INTO shots_tbl VALUES (NULL, ?, ?, ?)");
            ps.setString(1, sessionId);
            ps.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
            ps.setBinaryStream(3, is, is.available());
            int i = ps.executeUpdate();
            System.out.println(i + " records added");
        } catch (Exception e) {
            logger.error(e, e);
        }
    }    

}
